package com.woodws.sys.security;

import com.woodws.sys.entity.SysAccount;
import com.woodws.sys.entity.AccountInfo;
import com.woodws.sys.entity.SysRole;
import com.woodws.sys.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * Created by maoxiaodong on 2016/10/25.
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private AccountService accountService;

    @Autowired
    private RoleService roleService;

    @Autowired
    private UserService userService;

    @Autowired
    private UserRoleService userRoleService;

    @Autowired
    private RolePermissionService rolePermissionService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysAccount account = accountService.findByUsername(username);
        account.setUser(userService.find(account.getUserId()));
        List<Long> roleIds = userRoleService.findRoleIdByUserId(account.getUserId());
        List<SysRole> roles = roleService.findByIdIn(roleIds);

        Set<GrantedAuthority> grantedAuths = obtainGrantedAuthorities(roles);
        AccountInfo accountInfo = new AccountInfo(account, grantedAuths);
        accountInfo.addAttr("mainMenus",rolePermissionService.findUserMainMenus(roleIds));
        return accountInfo;
    }

    private Set<GrantedAuthority> obtainGrantedAuthorities(List<SysRole> roles) {
        Set<GrantedAuthority> authSet = new HashSet<GrantedAuthority>();
        for (SysRole role : roles) {
            authSet.add(new SimpleGrantedAuthority(role.getCode()));
        }
        return authSet;
    }
}
